package com.ripplezjw.blog.controller.admin;

import com.ripplezjw.blog.Service.ClassificationService;
import com.ripplezjw.blog.po.Classification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class ClassificationInputController {
    @Autowired
    ClassificationService classificationService;

    @GetMapping("clsInput")
    public String clsInput() {
        return "/admin/input/clsInput";
    }

    @PostMapping("clsInputTo")
    public String clsInputTo(Classification classification,
                             RedirectAttributes redirectAttributes) {
        String msg = classificationService.addClassification(classification);
        // 插入成功
        if (msg.isEmpty()) return "redirect:/admin/classificationMan";
        else {
            // 插入失败
            redirectAttributes.addFlashAttribute("cls_input_error_msg", msg);
            return "redirect:/admin/clsInput";
        }
    }

    @GetMapping("/clsDel/{clsId}")
    public String clsDel(Model model,
                         @PathVariable("clsId") int clsId) {
        classificationService.clickDelUserBtn(clsId);
        return "redirect:/admin/classificationMan";
    }

    @GetMapping("/clsMod/{clsId}")
    public String clsMod(@PathVariable("clsId") int clsId,
                         Model model) {
        Classification classification = classificationService.clickModUserBtn(clsId);
        model.addAttribute("cls", classification);
        return "/admin/input/clsMod";
    }

    @PostMapping("/clsMod/{clsId}/to")
    public String clsModTo(@PathVariable("clsId") int clsId,
                           Classification classification,
                           RedirectAttributes redirectAttributes) {
        classification.setClsId(clsId);
        String msg = classificationService.modUser(classification);
        // 更新成功
        if (msg.isEmpty()) return "redirect:/admin/classificationMan";
        else {
            // 更新失败
            redirectAttributes.addFlashAttribute("cls_input_error_msg", msg);
            return "redirect:/admin/clsMod/" + classification.getClsId();
        }
    }
}
